<template>
  <eui-background type="common">
    <eui-navbar ref="EuiNavBar" :title="title" :storeName="sUserStoreName" :storeId="sUserStore" displayable="true" />
    <view class="top-view">
      <eui-search-bar ref="RdsSearchBar" v-model="searchText" placeholder="请输入商品条码、编码" leftIcon="icon-saoyisao"
                      @confirm="searchConfirm"  @leftIconClick="clickScanRight" radius="30" :readonly="mainData.c_status != '0' || !['1','4'].includes(mainData.c_approve_status)">
      </eui-search-bar>
    </view>
    <eui-card hPadding="28">
      <eui-card-input v-model="mainData.c_adno" title="部门" h-padding="0" type="textname" :name="getRelatedName('rdsDeparts', mainData.c_adno)"
                      ref="cardAdnoInput" alignType="left" required="true" :rightIconType="detailData.length > 0 ? '' : 'right'"
                      @iconClick="clickRight('c_adno')"/>
      <eui-card-input v-model="mainData.c_wno" title="仓库"  h-padding="0" type="textname" :name="getRelatedName('rdsWnos', mainData.c_wno)"
                      ref="cardAdnoInput" alignType="left" required="true" :rightIconType="detailData.length > 0 ? '' : 'right'"
                      @iconClick="clickRight('c_wno')"/>
      <eui-card-input v-model="mainData.c_pal_kind" :range="getDictSelect({ dataItem: '损溢性质', excludeDTIds: ['3'] })" title="损溢性质" placeholder="请输入商品条码" h-padding="0" alignType="left"
                      ref="cardReqPrivInput" type="radio" :displayable="detailData.length > 0" rightIconType="right" required="true" />
      <view class="item-view">
        <eui-text type="price2" title="总数量" :value="mainData.c_n_l" :valueStyle="showRightStyle"/>
        <eui-text type="price2" title="成本额" :value="mainData.c_at_cost_l" :valueStyle="showRightStyle"/>
        <eui-text type="price2" title="不含税成本额" :value="mainData.c_aet_cost_l" :valueStyle="showRightStyle"/>
        <eui-text type="price2" title="售价额" :value="mainData.c_at_sale_l" :valueStyle="showRightStyle"/>
      </view>
    </eui-card>
    <view class="footer-view" :style="{ height: listHeight + 'rpx' }">
      <scroll-view scroll-y="true" style="height: 100%;">
        <view style="display:flex;flex-direction: column">
          <eui-card hPadding="28" v-if="detailData && detailData.length > 0">
            <eui-swipe-action>
              <view :ref="'dataItem' + index" v-for="(item, index) in detailData" :key="index" @click="onClickGdsInfo(item, index)">
                <eui-swipe-actionitem :ref="`swipeActionItem${index}`" :right-options="options" show="none" :auto-close="true"
                                      @change="change" @click="bindClick($event, index)" :disabled="mainData.c_status != '0'">
                  <view class="item-view">
                    <eui-text type="name2" :value="index + 1 + '. ' + '[' + item.c_gcode + ']' + item.c_gname" cWidth="width: 100%" />
                    <eui-text type="name2" :value="item.c_barcode" title="主条码" />
                    <eui-text type="slash2" :value="item.c_pack" :name="item.c_unit" title="含量/单位"/>
                    <eui-text v-if="sysConfig.inputType === '1'" type="price2" :value="item.c_n_pack" title="件数" :valueStyle="showRightStyle" :precision="0"/>
                    <eui-text v-if="sysConfig.inputType === '1'" type="price2" :value="item.c_n_odd" title="零数" :valueStyle="showRightStyle" :precision="3"/>
                    <eui-text v-if="sysConfig.inputType === '2'" type="price2" :value="item.c_n_input" title="包装数" :valueStyle="showRightStyle" :precision="3"/>
                    <eui-text type="price2" title="数量" :value="item.c_n" :valueStyle="showRightStyle" :precision="3" />
                    <eui-text type="price2" title="成本价" :value="item.c_pt_cost" :valueStyle="showRightStyle"/>
                    <eui-text type="price2" title="售价" :value="item.c_price" :valueStyle="showRightStyle"/>
                    <eui-text type="price2" title="成本额" :value="item.c_at_cost" :valueStyle="showRightStyle"/>
                    <eui-text type="price2" title="售价额" :value="item.c_at_sale" :valueStyle="showRightStyle"/>
                    <eui-text type="name2" :value="item.c_reason" title="报损原因" cWidth="width: 100%" />
                    <eui-text type="name2" :value="item.c_note" title="备注" cWidth="width: 100%" :valueStyle="noteStyle" />
                  </view>
                </eui-swipe-actionitem>
              </view>
            </eui-swipe-action>
          </eui-card>
        </view>
      </scroll-view>
    </view>
    <view class="bottom-view">
      <view class="center-style">
        <eui-button type="max2" title="保存" singleTag="保存" @buttonClick="buttonClick"
                    :disabled="!(mainData.c_status == '0' && ['1','4'].includes(mainData.c_approve_status) && detailData.length > 0)"/>
        <view class="gap-view" />
        <eui-button type="max" :title="sysConfig.isApprove ? '审批' : '审核'" singleTag="审核" @buttonClick="buttonClick"
                    :disabled="!(mainData.c_status == '0' && ['1','4'].includes(mainData.c_approve_status) && detailData.length > 0)" />
      </view>
    </view>
    <eui-popup ref="gdsPopup" background-color="#f8f8f8" type="bottom" :mask-click="false">
      <view class="popup-content">
        <view style="padding: 20rpx 20rpx 0 20rpx">
          <view class="item-view">
            <eui-text :value="'[' + currentGds.c_gcode + ']' + currentGds.c_gname" type="name2"
                      title="商品" occupy cWidth="width: 100%" />
            <eui-text v-model="currentGds.c_barcode" type="name2" title="主条码" />
            <eui-text v-model="currentGds.c_adno" type="titlename2" title="部门"
                      :name="getName('rdsDeparts', currentGds.c_adno)" />
            <eui-text :value="getName('rdsGdsclasses', currentGds.c_ccode)" type="name2"
                      title="品类" />
            <eui-text :value="getDictName('物流模式', currentGds.c_d_type)" type="name2" title="物流模式" />
            <eui-text :value="currentGds.c_pack" :name="currentGds.c_unit" type="slash2"
                      title="含量/单位" />
            <eui-text :value="currentGds.c_n_inv" type="price2" title="库存数量" :valueStyle="showRightStyle"/>
            <eui-text :value="currentGds.c_pt_cost" type="price2" title="成本价" :valueStyle="showRightStyle"/>
            <eui-text :value="currentGds.c_price" type="price2" title="售价" :valueStyle="showRightStyle"/>
            <eui-text :value="currentGds.c_at_cost" type="price2" title="成本额" :valueStyle="showRightStyle"/>
            <eui-text :value="currentGds.c_at_sale" type="price2" title="售价额" :valueStyle="showRightStyle"/>
            <eui-text :value="currentGds.c_tax_rate" type="price2" title="税率(%)" :valueStyle="showRightStyle"/>
            <eui-text :value="currentGds.c_deduct_rate" type="price2" title="扣率(%)" :valueStyle="showRightStyle"/>
            <eui-text :value="currentGds.c_aet_cost" type="price2" title="不含税成本额" :valueStyle="showRightStyle"/>
            <eui-text :value="currentGds.c_pt_in" type="price2" title="进价" :valueStyle="showRightStyle"/>
          </view>
          <view class="item-view" v-if="mainData.c_status != '0' || !['1','4'].includes(mainData.c_approve_status)">
            <eui-text v-if="sysConfig.inputType === '1'" type="price2" :value="currentGds.c_n_pack" title="件数" :valueStyle="showRightStyle" :precision="0"/>
            <eui-text v-if="sysConfig.inputType === '1'" type="price2" :value="currentGds.c_n_odd" title="零数" :valueStyle="showRightStyle" :precision="3"/>
            <eui-text v-if="sysConfig.inputType === '2'" type="price2" :value="currentGds.c_n_input" title="包装数" :valueStyle="showRightStyle" :precision="3"/>
            <eui-text :value="currentGds.c_n" type="price2" title="数量" style="color:red"
                      :precision=3 :valueStyle="showRedStyle"/>
            <eui-text v-model="currentGds.c_reason" type="name2" title="报损原因" occupy cWidth="width: 100%" />
            <eui-text v-model="currentGds.c_note" type="name2" title="备注" occupy
                      cWidth="width: 100%; margin-bottom: 20rpx" :valueStyle="noteStyle"/>
          </view>
          <view v-if="mainData.c_status == '0' && ['1','4'].includes(mainData.c_approve_status)">
            <eui-card-input v-if="sysConfig.inputType === '1'" v-model="currentGds.c_n_pack" type="number" title="件数" :required="true"
                            fieldName="c_n_pack" @confirm="validateDetail" isBlur ref="cardNPackInput"
                            placeholder="请输入件数" maxlength="9" alignType="left" :focus="true" />
            <eui-card-input v-if="sysConfig.inputType === '1'" v-model="currentGds.c_n_odd" type="number" title="零数" :required="true"
                            fieldName="c_n_odd" @confirm="validateDetail" isBlur ref="cardNOddInput"
                            placeholder="请输入零数" maxlength="9" alignType="left" />
            <eui-card-input v-if="sysConfig.inputType === '2'" v-model="currentGds.c_n_input" type="number" title="包装数" :required="true"
                            fieldName="c_n_input" @confirm="validateDetail" isBlur ref="cardNIptInput"
                            placeholder="请输入包装数" maxlength="9" alignType="left" :focus="true" />
            <eui-card-input :value="currentGds.c_n" type="number" title="数量" placeholder="" :displayable="true" alignType="left" />
            <eui-card-input v-model="currentGds.c_reason" title="报损原因" type="selector"
                            :range="reasonSelectList" alignType="left" fieldName="c_reason"
                            placement="top" placeholder="请选择原因"/>
            <eui-card-input v-model="currentGds.c_note" title="备注" isBlur fieldName="c_note"
                            maxlength="100" alignType="left" />
          </view>
        </view>
        <view class="popup-bottom flex-1 flex">
          <eui-button type="max2" title="关闭" singleTag="关闭" @buttonClick="buttonClick"></eui-button>
          <eui-button type="max" title="确认" singleTag="确认" @buttonClick="buttonClick" :disabled="mainData.c_status != '0'"></eui-button>
        </view>
      </view>
    </eui-popup>
  </eui-background>
</template>

<script setup type="ts">
import {onMounted, ref, reactive} from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { validateStores, validateGds, defaultMapping  } from '@/hooks/useValidateMethod';
import service from "@/common/service";
import {getRdsUrl, rdsRequest, rdsRequestAsync} from '@/hooks/rdsServices';
import { calcAtInByPt, validateOddLot, round, calcPetpayByPtPay } from '@/hooks/useCalculateMethod';
import { useMainStore } from "@/store/modules/store";
import { useLoginStore } from "@/store/modules/useLoginStore";
import { getRelatedName, getDictName, getUserDictSelectList, getDictSelect, getDictSelectList, getWeightUnits } from '../components/RelatedName.js';
import { init, getRdsUserDepartAuthority, getRdsSysConfig } from '@/hooks/init';
import dateRangUtil from "@/common/dateRangUtil";
import { validateAdnoLevel } from '@/hooks/useBillInfo';
import Enjoy from "@/common/enjoy";

const rdsUrl = getRdsUrl();
const isOpened = ref('none');
const mainStore = useMainStore();
const LoginStore = useLoginStore();
const listHeight = ref(300);
const noteStyle = ref('white-space: nowrap;overflow: hidden;text-overflow: ellipsis');

const sUserStore = ref('');
const sUserStoreName = ref('');
const sUser = ref('');
const isCurrentGds = ref([]);
const title = ref('新增报损');
const height = ref(0);
const width = ref(0);
const c_disabled = ref(false);
const c_status = ref('0');
const searchText = ref('');
const options = ref([{
  text: '删除',
  style: {
    backgroundColor: '#F56C6C',
  }
}]);
const showRightStyle = ref('text-align: right');
const showRedStyle = ref('text-align: right;color: #FF4000;');
const sysConfig = ref({
  isBarcode: 0, // 0-否 1-是，默认为否，是：启用时则支持按箱码订货，否则不支持按箱码订货
  isApprove: '',//商品验收单是否审批
  inputType: '1' // 1-件数零数分别录入方式 2-自动识别含量单值录入方式
});
const uniFabContent = ref( [
  {
    text: '删除单据'
  },
]);
const reasonSelectList = ref([]);
const detailData = ref([]);
const listManager = ref([]);
let delList = reactive([]);
let newList = reactive([]);
let modifiedList = reactive([]);
const currentGds = ref({});
const currentGdsIndex = ref(0);
const mainData = ref({
  c_tenant_id: '',
  c_id: '',
  c_bill_type: '7F1',
  c_status: '0',
  c_mk_type: '3',
  c_gmode: '',
  c_property_group: '',
  c_pal_kind: '1',//进货损溢
  c_pal_flag: '1',//报损
  c_store_id: sUserStore.value,
  c_store_name: sUserStoreName.value,
  c_rec_store_type: '',
  c_wno: '00',
  c_wname: '本部',
  c_adno: '',
  c_org_no: '',
  c_req_userno: sUserStore.value,
  c_charge_userno: '',
  c_send_wms: '',
  c_send_wms_dt: null,
  c_n_l: 0,
  c_at_pay_l: 0,
  c_aet_pay_l: 0,
  c_at_cost_l: 0,
  c_aet_cost_l: 0,
  c_at_sale_l: 0,
  c_mk_store_id: sUserStore.value,
  c_mk_store_name: sUserStoreName.value,
  c_mk_dt: dateRangUtil.formatDate(new Date(),'YYYY-MM-DD HH:mm:ss'),
  c_mk_userno: sUser.value,
  c_approve_status: '1',
  c_approve_dt: null,
  c_au_dt: null,
  c_au_userno: '',
  c_void_dt: null,
  c_void_userno: '',
  c_print_dt: null,
  c_print_userno: '',
  c_print_n: 0,
  c_orig_id: '',
  c_orig_type: '',
  c_src_id: '',
  c_src_type: '',
  c_note: '',
  c_sys_note: '',
  c_n_p: 0,
  c_at_pay_p: 0,
  c_aet_pay_p: 0,
  c_at_cost_p: 0,
  c_aet_cost_p: 0,
  c_at_sale_p: 0,
});
const btnSaveEnabled = ref(true);
const gdsPopup = ref(null);
const RdsSearchBar = ref(null);
const cardNPackInput = ref(null);
const cardNOddInput = ref(null);
const cardNIptInput = ref(null);

onMounted(() => {
  getListHeight()
})

// 获取列表高度
const getListHeight = async () => {
  await uni.getSystemInfo({
    success: function (res) { // res - 各种参数
      let info = uni.createSelectorQuery().select(".footer-view");
      info.boundingClientRect(function (data) { //data - 各种参数
        //获取列表高度
        let height = res.windowHeight - data.top;
        //转换rpx
        let finalHeight = height / (res.windowWidth / 750) - 100;
        listHeight.value = finalHeight;
      }).exec()
    }
  });
};

onLoad(async (option) => {
  const { loginInfo } = mainStore;
  await setDefault(option);
  if (option.c_id) {
    title.value = option.c_id;
    service.enjoyShowLoading("正在加载...")
    await billQuery();
    service.enjoyHideLoading();
  }
  await getSysConfig();
  if(!loginInfo.sCurrentAdno){
    return;
  }
  //验证部门层级
  if (!mainData.value.c_id) {
    const result = await validateAdnoLevel({ IuputData: loginInfo.sCurrentAdno, billKind: "50", tenantId: loginInfo.idsToken.tenantid });
    if (result && !result.HasException) {
      const userAdno = await getRdsUserDepartAuthority();
      if (userAdno.includes(loginInfo.sCurrentAdno)) {
        mainData.value.c_adno = loginInfo.sCurrentAdno;
      }
    }
  }
})

const setDefault = async (option) => {
  const { loginInfo } = mainStore;
  sUserStore.value = option.storeId;
  sUserStoreName.value = getName('rdsStores', option.storeId);
  sUser.value = loginInfo.sUser;
  mainData.value.c_id = option.c_id;
  mainData.value.c_store_id = option.storeId;
  mainData.value.c_store_name = sUserStoreName.value;
  mainData.value.c_rec_store_id = option.storeId;
  mainData.value.c_mk_store_id = option.storeId;
  //损益原因
  let reasonList = getDictSelectList('损溢原因');
  reasonList.forEach(item => {
    item.value = item.text;
  });
  reasonSelectList.value = reasonList;
}

const getSysConfig = async () => {
  sysConfig.value.isBarcode = await getRdsSysConfig("进销存管理参数", "是否支持按箱码订货");
  sysConfig.value.isApprove = await getRdsSysConfig("单据是否审批", "损溢申请单") === '是';
  sysConfig.value.inputType = await getRdsSysConfig("供应链管理参数", "商品件数零数录入方式") || '1';
}

// 扫码
const clickScanRight = (type) => {
  uni.scanCode({
    success: async function (res) {
      if (res.result != '' && res.result != undefined && res.result != null) {
        searchText.value = res.result;
        await searchConfirm({
          value: res.result
        });
      }
    }
  });
}

const validateDetail = async (args) => {
  const { type, fieldName, oldValue, newValue, itemIndex } = args;

  let result = null;
  let weightUnits;
  let validateResult;
  let c_n;
  switch (fieldName) {
    case 'c_n_pack':
      currentGds.value.c_n_pack = parseInt(newValue);
      c_n = currentGds.value.c_n_pack * currentGds.value.c_pack + currentGds.value.c_n_odd;
      currentGds.value.c_n = c_n;
      currentGds.value.c_n_input = round(c_n / currentGds.value.c_pack, 3);
      calcRowAmount(currentGds.value);
      break;
    case 'c_n_odd':
      weightUnits = await getWeightUnits();
      if (!weightUnits.includes(currentGds.value.c_unit)) {
        if (newValue % 1 > 0) {
          uni.showToast({
            duration: 2000,
            icon: 'none',
            title: '本商品数量不允许录入小数，仅重量单位商品可以录入小数'
          });
          setTimeout(() => {
            cardNOddInput.value.getFocus();
          }, 300);
          return;
        }
      }
      currentGds.value.c_n_odd = newValue;
      validateResult = validateOddLot(newValue, currentGds.value.c_n_pack, currentGds.value.c_pack, '1');
      result = validateResult.result;
      if (!result || result?.validated) {
        currentGds.value.c_n = validateResult.n;
        currentGds.value.c_n_pack = validateResult.npack;
        currentGds.value.c_n_input = round(currentGds.value.c_n / currentGds.value.c_pack, 3);
        if (validateResult.result) {
          currentGds.value.c_n_odd = validateResult.result?.retValue;
        }
        calcRowAmount(currentGds.value);
      } else {
        uni.showToast({
          duration: 2000,
          icon: 'none',
          title: result?.message
        });
        setTimeout(() => {
          currentGds.value.c_n_odd = oldValue;
          // this.$refs.cardNOddInput.inputValue = oldValue;
        }, 300);
      }
      break;
    case 'c_n_input':
      const c_n_odd = round(newValue * currentGds.value.c_pack, 3);
      validateResult = validateOddLot(c_n_odd, currentGds.value.c_n_pack, currentGds.value.c_pack, '1', true);
      result = validateResult.result;
      if (!result || result?.validated) {
          weightUnits = await getWeightUnits();
          if (!weightUnits.includes(currentGds.value.c_unit)) {
              if (newValue % 1 > 0) {
                  uni.showToast({
                      duration: 2000,
                      icon: 'none',
                      title: '本商品的包装零数不允许为小数，仅重量单位商品的零数允许为小数'
                  });
                  setTimeout(() => {
                      cardNIptInput.value.getFocus();
                  }, 300);
                  return;
              }
          }
        currentGds.value.c_n = validateResult.n;
        currentGds.value.c_n_pack = validateResult.npack;
        currentGds.value.c_n_input = round(currentGds.value.c_n / currentGds.value.c_pack, 3);
        if (result) {
          currentGds.value.c_n_odd = result.retValue;
        }
        calcRowAmount(currentGds.value);
      }
      break;
    case 'c_n':
        weightUnits = await getWeightUnits();
        if (!weightUnits.includes(currentGds.value.c_unit)) {
            if (newValue % 1 > 0) {
                uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '本商品数量不允许录入小数，仅重量单位商品可以录入小数'
                });
                return;
            }
        }
      validateResult = validateOddLot(newValue, currentGds.value.c_n_pack, currentGds.value.c_pack, '1');
      result = validateResult.result;
      if (!result || result?.validated) {
        currentGds.value.c_n = validateResult.n;
        currentGds.value.c_n_pack = validateResult.npack;
        currentGds.value.c_n_input = round(currentGds.value.c_n / currentGds.value.c_pack, 3);
        if (result) {
          currentGds.value.c_n_odd = result.retValue;
        }
        calcRowAmount(currentGds.value);
      }
      break;
  }
}

const buttonClick = async (t) => {
  const { loginInfo } = mainStore;
  let { singleTag } = t;
  switch (singleTag) {
    case '保存':
      // 保存
      if (detailData.value.length <= 0) {
        uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '商品不能为空！'
        });
        return;
      }
      service.enjoyShowLoading('正在保存...');
      await saveBill();
      await billQuery();
      service.enjoyHideLoading();
      break;
    case '审核':
      // 审核
      if (detailData.value.length <= 0) {
        uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '商品不能为空！'
        });
        return;
      }
      await saveBill();
      const req = {
        BillId: mainData.value.c_id,
        UserNo: loginInfo.sUser,
        StoreId: mainData.value.c_store_id,
      }

      if (sysConfig.value.isApprove && mainData.value.c_status == '0') { // 审批
        await approve(req);
      }
      if (!sysConfig.value.isApprove && mainData.value.c_status == '0') { // 审核
        await auditBill(req);
      }
      break;
    case '关闭':
      gdsPopup.value.close();
      RdsSearchBar.value.clear();
      break;
    case '确认':
      service.enjoyShowLoading("正在加载...");
      currentGds.value.rowType = (currentGds.value.rowType === 1 || currentGds.value.rowType === undefined) ? 1 : 2;
      detailData.value[currentGdsIndex.value] = currentGds.value;
      service.enjoyHideLoading();
      setTimeout(() => {
        listManager.value = detailData.value;
        gdsPopup.value.close();
        RdsSearchBar.value.clear();
        calcMainAmount();
      }, 300);
      break;
  }
}

const trigger = (e) => {
  if (!mainData.value.c_id) {
    uni.showToast({
      duration: 3500,
      icon: 'none',
      title: '单据号不能为空！'
    });
    return false;
  }
  const { loginInfo } = mainStore;
  const req = {
    BillId: mainData.value.c_id,
    UserNo: loginInfo.sUser,
  }
  switch (e.item.text) {
    case '删除单据':
      if (mainData.value.c_status == "0") {
        uni.showModal({
          title: ' 提示',
          content: '请确认，删除单据[' + req.BillId + ']?',
          showCancel: true,
          success: async (res) => {
            if (res.confirm) {
              service.enjoyShowLoading('正在删除...');
              const result = await rdsRequest(rdsUrl.scApi, '损溢申请单', 'EnjoyBillDelete', req, '7F1');
              service.enjoyHideLoading();
              uni.showToast({
                duration: 3500,
                icon: 'none',
                title: '操作成功'
              });
              uni.redirectTo({
                url: './index'
              });
            }
          }
        });
      }
      break;
  }
}

// 保存数据
const saveBill = async () => {
  const flag = mainData.value.c_id;
  let reqBillId = mainData.value.c_id;
  if (!flag) {
    const getBilllIdReq = {
      BillIdKeyValue: {
        key: "c_id",
        value: ""
      },
      BillVariable: "",
      TableName: "tb_po_pal",
      BillName: "损溢申请单"
    }
    const billlId = await rdsRequest(rdsUrl.mainApi, '单号生成服务', 'EnjoyGetBillId', getBilllIdReq, '7F1');
    if (billlId) {
      mainData.value.c_mk_userno = sUser.value;
      mainData.value.c_mk_store_id = sUserStore.value;
      reqBillId = billlId;
    }
  } else {
    mainData.value.c_req_userno = sUser.value;
    mainData.value.c_modify_userno = sUser.value;
    mainData.value.c_modify_dt = dateRangUtil.formatDate(new Date(),'YYYY-MM-DD HH:mm:ss');
  }
  let listData = {
    ...mainData.value,
    c_id: reqBillId,
  };

  detailData.value.forEach(x => x.c_id = reqBillId)
  newList = detailData.value.filter(x => x.rowType == 1 || !x.hasOwnProperty('rowType'));
  modifiedList = detailData.value.filter(x => x.rowType == 2);
  const req = {
    NewList: flag ? [] : [listData],
    ModifiedList: flag ? [listData] : [],
    DelList: [],
    TableName: "tb_po_pal",
    PrimaryKeys: ["c_tenant_id", "c_id"],
    ChildData: [{
      ChildTableName: "tb_po_pal_g",
      ParentTableName: "tb_po_pal",
      ChildColumnNames: ["c_id"],
      ParentColumnNames: ["c_id"],
      ChildSaveModel: {
        NewList: newList,
        ModifiedList: modifiedList,
        DelList: delList,
        TableName: "tb_po_pal_g",
        PrimaryKeys: ["c_tenant_id", "c_id", "c_gsort"],
      },
    }],
    BillSet: {
      BillIdKeyValue: {
        key: "c_id",
        value: reqBillId
      },
      BillVariable: "",
      TableName: "tb_po_pal",
      BillName: "损溢申请单"
    },
  };
  const result = await rdsRequest(rdsUrl.scApi, '损溢申请单', 'EnjoyBillSaveNew', req, '7F1');
  if (result && result.BillId) {
    mainData.value.c_id = reqBillId;
    title.value = reqBillId;
  }
  uni.showToast({
    duration: 2000,
    icon: 'none',
    title: `保存成功`
  });
  newList = [];
  modifiedList = [];
  delList = [];
}

const setClass = async (itemIndex) => {
  isCurrentGds.value = Array(isCurrentGds.value.length).fill(false);
  isCurrentGds.value[itemIndex] = true;
}

const palKindInput = (value) => {
  mainData.value.c_pal_kind = value;
}

// 获取单据详情信息
const billQuery = async (type) => {
  if (!mainData.value.c_id) {
    return;
  }
  service.enjoyShowLoading('正在加载...');
  const req = {
    BillId: mainData.value.c_id,
  };
  const result = await rdsRequest(rdsUrl.scApi, '损溢申请单', 'EnjoyBillQuery', req, '7F1');
  if (result.ds.length > 0) {
    mainData.value = result.ds[0];
    detailData.value = result.ds1;
    detailData.value.forEach(x => {
      x.rowType = 0;
    })
    title.value = mainData.value.c_id + '详情'
  } else {
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '未查询到数据',
      mask: true,
    });
  }
  if (type && type === '审批') {
    service.enjoyHideLoading();
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '发送审批成功！'
    });
  } else if (type && type === '审核') {
    service.enjoyHideLoading();
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '审核成功！'
    });
  }
}

const searchConfirm = async (e) => {
  if (!e || !e.value) {
    return;
  }
  let searchValue = e.value;
  if (!mainData.value.c_adno) {
    uni.showToast({
      title: '请先选择部门!',
      icon: 'none',
      duration: 2000,
    });
    setTimeout(() => {
      clickRight('c_adno')
    }, 1000);
    return;
  }
  // 检查当前机构是否为 分店或配送中心，否则不允许新建
  const result = await validateStores(
      { fieldName: 'c_store_id', newValue: sUserStore.value },
      { ischecklimit: true, firstValueMode: true }
  );
  if (!['2', '3'].includes(result.c_type)) {
    uni.showToast({
      title: '当前机构不允许报损,请切换至分店或配送中心!',
      icon: 'none',
      duration: 3000,
    });
    setTimeout(() => {
      clickRight('c_store_id')
    }, 1000);
    return;
  }
  searchText.value = searchValue;

  const itemIndex = detailData.value.findIndex(i => i.c_barcode === searchValue || (i.c_gcode === searchValue && ((i.c_pack === 1 && sysConfig.value.isBarcode == '1') || !('c_barcode' in i))));
  if (itemIndex !== -1) {
    service.enjoyShowLoading('正在加载...');
    // //计算当前商品所在页数
    // const page = Math.ceil(itemIndex / 10);
    // //如果商品所在页数大于当前页数，刷新到当前页数
    // if (this.currentPage < page) {
    //   this.currentPage = page;
    //   this.$refs.paging.refreshToPage(Math.ceil(itemIndex / 10));
    // }
    // setTimeout(() => {
    //   //定位到当前商品
    //   this.$refs.paging.scrollIntoViewById(`item-${itemIndex}`, 300, true);
    // }, 300);
    onClickGdsInfo(detailData.value[itemIndex], itemIndex)
    service.enjoyHideLoading();
  } else {
    if (mainData.value.c_status != '0') {
      const itemIndex = detailData.value.findIndex(i => i.c_barcode === searchValue || i.c_gcode === searchValue);
      if (itemIndex !== -1) {
        // service.enjoyShowLoading('正在加载...');
        // //计算当前商品所在页数
        // const page = Math.ceil(itemIndex / 10);
        // //如果商品所在页数大于当前页数，刷新到当前页数
        // if (this.currentPage < page) {
        //   this.currentPage = page;
        //   this.$refs.paging.refreshToPage(Math.ceil(itemIndex / 10));
        // }
        // setTimeout(() => {
        //   //定位到当前商品
        //   this.$refs.paging.scrollIntoViewById(`item-${itemIndex}`, 300, true);
        // }, 300);
        // service.enjoyHideLoading();
      } else {
        uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '未查询到商品'
        });
      }
      return;
    }
    currentGds.value = initRow();
    let args = { fieldName: 'c_gcode', row: currentGds.value, newValue: searchText.value, };
    service.enjoyShowLoading('正在加载...');
    const result = await validateGds({
      url: rdsUrl.scApi, uniqueKey: '损溢申请单', billType: '7F1', args,
      head: {
        level: '1',
        code: mainData.value.c_store_id,
        adno: mainData.value.c_adno,
        value_mode: 'F',
        sample_code: '',
        login_store: sUserStore.value,
        wno: mainData.value?.c_wno,
      },
      listManager: detailData.value,
      mapping: [
        //['现表字段','带出字段']//第一条数据调出方，第二条数据调入方
        ...defaultMapping,
        ['c_od_day', 'c_od_day'],
        ['c_od_unit', 'c_od_unit'],
        ['c_type', 'c_type'], //商品类型
        ['c_order_pack', 'c_order_content'],
        ['c_bcode', 'c_bcode'], //品牌
        ['c_gname', 'c_name'],
        ['c_unit', 'c_unit'], //单位
        ['c_tax_rate', 'c_tax_rate'], //税率
        ['c_price', 'c_price'],
        ['c_deduct_rate', 'c_deduct_rate'],
        ['c_pt_pay', 'c_pt_pay'],
        ['c_pet_pay', 'c_pet_pay'],
        ['c_pt_in', 'c_pt_in'],
        ['c_pt_cost', 'c_pt_cost'],
        ['c_pt_type', 'c_pt_type'],
        ['c_tax_rate_pay', 'c_tax_rate_pay'],
        ['c_tax_src', 'c_tax_src'],
        ['c_provider', ''],
        ['c_provider_name', ''],
        // ['c_con_type', 'c_con_type'],
        // ['c_con_no', 'c_con_no'],
        ['c_pay_type', 'c_pay_type'],
        ['c_pack', 'c_pack'],
        ['c_n', ''], // 数量重置
        ['c_n_inv', 'c_n_inv'], // 库存
      ],
      initRow: initRow,
      callback: async (items) => {
        detailData.value.forEach(item => {
          items.forEach(x => {
            if (item.c_gcode === x.c_gcode && !item.c_pt_cost) {
              item.c_pt_cost = x.c_pt_in;
            }
          });
        });
        items.forEach(x => {
          x.c_pack = sysConfig.value.isBarcode == '1' ? x.c_n : x.c_content;
        });
        return { cancel: false }
      }
    })


    if (result) {
      listManager.value = detailData.value;
      currentGdsIndex.value = detailData.value.findIndex(i => i.c_barcode === result.c_barcode);

      onClickGdsInfo(detailData.value[currentGdsIndex.value], currentGdsIndex.value)

      // setTimeout(() => {
      //   //计算当前商品所在页数
      //   const page = Math.ceil(this.currentGdsIndex / 10);
      //   //如果商品所在页数大于当前页数，刷新到当前页数
      //   if (this.currentPage < page) {
      //     this.currentPage = page;
      //     this.$refs.paging.refreshToPage(page);
      //   }
      //   //定位到当前商品
      //   this.$refs.paging.scrollIntoViewById(`item-${this.currentGdsIndex}`, 300, true);
      // }, 300);
    }
    service.enjoyHideLoading();
  }
}

const getName = (key, value) => {
  return getRelatedName(key, value);
}

const getSelectList = (key) => {
  return getDictSelect(key);
}

// 计算当前金额
const calcRowAmount = (row) => {
  const { c_n, c_n_odd, c_n_pack, c_pt_cost, c_price, c_pt_pay, c_pet_pay, c_tax_rate, c_tax_src } = row;
  // 含税成本金额 c_at_cost
  currentGds.value.c_at_cost = calcAtInByPt({ c_pt: c_pt_cost, c_n: c_n });
  // 不含税成本金额 c_aet_cost
  currentGds.value.c_aet_cost = calcPetpayByPtPay({
    c_pt_pay: currentGds.value.c_at_cost,
    c_tax_rate_pay: c_tax_rate,
    c_tax_src: c_tax_src,
  });
  // 售价金额 c_at_sale
  currentGds.value.c_at_sale = calcAtInByPt({ c_pt: c_price, c_n: c_n });
  // 含税结算金额 c_at_pay
  currentGds.value.c_at_pay = calcAtInByPt({ c_pt: c_pt_pay, c_n: c_n });
  // 不含税结算金额  c_aet_pay
  currentGds.value.c_aet_pay = calcAtInByPt({ c_pt: c_pet_pay, c_n: c_n });
}

const initRow = (index) => {
  const sort = Math.max(0, ...detailData.value.map(f => f.c_gsort)) + 1 + (index || 0);
  return {
    c_tenant_id: '',
    c_id: '',
    c_gsort: sort,
    c_gcode: '',
    c_gname: '',
    c_barcode: '',
    c_type: '',
    c_adno: '',
    c_ccode: '',
    c_bcode: '',
    c_unit: '',
    c_pack: 0,
    c_tax_src: '',
    c_tax_rate_pay: 0,
    c_tax_rate: 0,
    c_pt_pay: 0,
    c_pet_pay: 0,
    c_pt_in: 0,
    c_pt_cost: 0,
    c_price: 0,
    c_deduct_rate: 0,
    c_pt_type: '',
    // c_orig_bat_id: null,
    c_orig_id: '',
    c_provider: '',
    c_con_type: '',
    c_con_no: '',
    c_pay_type: '',
    c_d_type: '',
    c_pal_flag: '1',
    c_n_inv: 0,
    c_n_req: 0,
    c_n_pack: 0,
    c_n_odd: 0,
    c_n_input: 0,
    c_n: 0,
    c_at_pay: 0,
    c_aet_pay: 0,
    c_at_cost: 0,
    c_aet_cost: 0,
    c_at_sale: 0,
    c_od_day: 0,
    c_od_unit: '',
    c_product_dt: null,
    c_expired_dt: null,
    c_serial_no: '',
    c_reason: '',
    c_pic_id: '',
    c_src_id: '',
    c_src_type: '',
    c_note: '',
    c_gds_flag: '',
    c_err_msg: '',
    // rowType:1,
  }
}

const onClickGdsInfo = (item, index) => {
  service.enjoyShowLoading('正在加载...');
  try {
    currentGdsIndex.value = index;
    currentGds.value = JSON.parse(JSON.stringify(item));
    currentGds.value.rowType = (currentGds.value.rowType === 1 || currentGds.value.rowType === undefined) ? 1 : 2;
    gdsPopup.value.open();
  } catch (error) {
    service.enjoyHideLoading();
  }
  service.enjoyHideLoading();
}

// 选择框点击事件
const clickRight = (type) => {
  let parms = Enjoy.GetDialogParms();
  parms.CallBack = SelectionChanged;
  if (type == 'c_store_id') {
    parms.SelectionType = "机构选择";
    parms.SelectedItems = mainData.value.c_store_id;
  } else if (type == 'c_adno') {
    parms.SelectionType = "部门选择";
    parms.SelectedItems = mainData.value.c_adno;
  } else if (type == 'c_wno') {
    parms.SelectionType = "仓库选择";
    parms.SelectedItems = mainData.value.c_wno;
    parms.SelectionStoreId = sUserStore.value;
  }
  Enjoy.OpenDialog(parms)
}

const SelectionChanged = async (e) =>{
  const { loginInfo } = mainStore;
  if (e.SelectionType=='部门选择') {
    //验证部门层级
    let curAdno = e.BackParms.Key;
    const validateResult = await validateAdnoLevel({ IuputData: curAdno, billKind: "7F", tenantId: loginInfo.idsToken.tenantid });
    if (validateResult && validateResult.HasException) {
      uni.showToast({
        duration: 3500,
        icon: 'none',
        title: validateResult.Exception.Message
      });
      setTimeout(() => {
        clickRight('c_adno')
      }, 1000);
      return;
    }
    const userAdno = await getRdsUserDepartAuthority();
    if (userAdno.includes(curAdno)) {
      mainData.value.c_adno = curAdno;
    } else {
      uni.showToast({
        duration: 3500,
        icon: 'none',
        title: `没有部门${curAdno}权限！`
      });
      setTimeout(() => {
        clickRight('c_adno')
      }, 1000);
      return
    }
    const lsGds = detailData.value.filter(i => i.c_gcode?.length > 0);
    if (lsGds.length > 0 && lsGds.some(i => i.c_adno.startsWith(curAdno) == false)) {
      uni.showToast({
        duration: 3500,
        icon: 'none',
        title: '录入部门与明细商品部门不匹配！'
      });
      setTimeout(() => {
        clickRight('c_adno')
      }, 1000);
      return;
    }
  } else if (e.SelectionType=='机构选择') {
    let curStoreId = e.BackParms.Key;
    const result = await validateStores(
        { fieldName: 'c_store_id', row: mainData.value, newValue: curStoreId },
        { ischecklimit: true, firstValueMode: true }
    );
    if (['2', '3'].includes(result.c_type)) {
      // 更新机构信息
      sUserStoreName.value = e.BackParms.Value;
      sUserStore.value = curStoreId;
      mainData.value.c_store_id = curStoreId;
      mainData.value.c_mk_store_id = curStoreId;
    } else {
      uni.showToast({
        duration: 3500,
        icon: 'none',
        title: '请选择分店或配送中心！'
      });
      setTimeout(() => {
        clickRight('c_store_id')
      }, 300);
    }
  } else if (e.SelectionType=='仓库选择') {
    mainData.value.c_wno = e.BackParms.Key;
  }
}

const change = (e) => {
  isOpened.value = e;
}

const bindClick = (e, index) => {
  uni.showModal({
    title: ' 提示',
    content: '您确定要删除数据吗？',
    showCancel: true,
    success: async (res) => {
      if (res.confirm) {
        delList.push(detailData.value[index]);
        detailData.value.splice(index, 1);
        listManager.value = detailData.value;
        calcMainAmount();
      }
    }
  });
}

const calcMainAmount = () => {
  mainData.value.c_n_l = detailData.value.reduce((pre, current) => pre + current.c_n, 0);
  mainData.value.c_at_sale_l = detailData.value.reduce((pre, current) => pre + current.c_at_sale, 0);
  mainData.value.c_aet_cost_l = detailData.value.reduce((pre, current) => pre + current.c_aet_cost, 0);
  mainData.value.c_at_cost_l = detailData.value.reduce((pre, current) => pre + current.c_at_cost, 0);
  mainData.value.c_aet_pay_l = detailData.value.reduce((pre, current) => pre + current.c_aet_pay, 0);
  mainData.value.c_at_pay_l = detailData.value.reduce((pre, current) => pre + current.c_at_pay, 0);
}

// 审批
const approve = (req) => {
  if (['1','4'].includes(mainData.value.c_approve_status)) {
    uni.showModal({
      title: ' 提示',
      content: '请确认，单据[' + req.BillId + ']发起审批?',
      showCancel: true,
      success: async (res) => {
        if (res.confirm) {
          await sendApprove();
        }
      }
    });
  } else {
    const { loginInfo } = mainStore;
    const item = {
      c_approve_status: mainData.value.c_approve_status,
      Id: mainData.value.c_id,
      UserNo: loginInfo.sUser,
      StoreId: mainData.value.c_store_id,
      AppParam: '损溢申请单',
    }
    const request = {
      Id: req.BillId,
      UserNo: loginInfo.sUser,
      StoreId: mainData.value.c_store_id,
    }
    // apps.ApprovePath(request, item, res => { }, res => { });
  }
}

// 审核
const auditBill = (req) => {
  if (mainData.value.c_status == '0') {
    uni.showModal({
      title: ' 提示',
      content: '请确认，审核单据[' + req.BillId + ']?',
      showCancel: true,
      success: async (res) => {
        if (res.confirm) {
          service.enjoyShowLoading('正在审核...');
          const result = await rdsRequestAsync(rdsUrl.scApi, '损溢申请单', 'EnjoyBillAudit', req, '7F1');
          if (result.HasException) {
            uni.showToast({
              duration: 2000,
              icon: 'none',
              title: result.Exception.Message
            });
          }
          await billQuery('审核');
        }
      }
    });
  }
}

const sendApprove = async () => {
  const { loginInfo } = mainStore;
  const ApproveBills = {
    AppPage: "/modules/ic/oper/lossReq/list",
    AppParam: "损溢申请单",
    AppUsers: [],
    BillId: mainData.value.c_id,
    BillKey: mainData.value.c_id,
    BillRealType: "损溢申请单",
    BillType: "损溢申请单",
    CFGName: "损溢申请单",
    FlowGuid: "e41e4780-fb44-407f-9757-95074e1ee46b",
    FlowName: "损溢申请单",
    HtmlContent: "",
    HtmlMobileContent: "",
    IsMainFlow: true,
    IsCanTempApp: false,
    IsSelected: true,
    IsTempApp: false,
    MdCode: "rds_ic_po_pal",
    NoticType: "",
    ProjectName: "RDS", // OA\RMIS\RMISNew,
    StoreId: mainData.value.c_store_id,
    AppReqUserNo: loginInfo.sUser,
    UserNo: loginInfo.sUser,
    TempTitle: `单据:${mainData.value.c_id}`,
    // ApproveServiceUrl: Url.EnjoyRMIS,
  }
  const approveResult = await rdsRequest(rdsUrl.apiApi, '审批处理', 'SendApprove', ApproveBills, '7F1');
  if (approveResult.Result) {
    await billQuery('审批');
  }
}

</script>

<style lang="scss" scoped>
@import '../../../main.scss';
.top-view {
  width: 100%;
  height: 88rpx;
}
.extra-view {
  margin-right: 30rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 60rpx;
  height: 100%;
}
.footer-view {
  width: 100%;
  flex: 1;
}
.list-scroll {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}
.bottom-view {
  width: 100%;
  height: 100rpx;
  background: #FFFFFF;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  flex-direction: row;
}
.center-style {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  margin-right: 20rpx;
  //gap: 20rpx;
}
.gap-view {
  width: 20rpx;
  height: auto;
}
//内容行
.item-view {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  align-items: center;
  margin-top: 16rpx;
  row-gap: 8rpx;
}
.line-view {
  width: 100%;
  height: 1rpx;
  background: #EEEEEE;
  margin: 20rpx 0;
}
.popup-content {
  align-items: center;
  justify-content: left;
  flex-direction: column;
  padding: 0;
  width: 100%;
  background-color: #ffffff;
}
.popup-bottom {
  background: #ffffff;
  border-top: 1rpx solid $uni-line-color;
  display: flex;
  justify-content: center;
  padding: 20rpx;
}
</style>
